package com.gzhryc.shared_device.oem.h5.mng.controllers.sys;

import com.gzhryc.common.config.DefaultEnum;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;
import com.gzhryc.system.MenuService;
import com.gzhryc.system.RoleService;
import com.gzhryc.system.dao.db.Menu;
import com.gzhryc.system.dao.db.Role;
import com.gzhryc.system.dao.enums.MenuEnum;
import com.gzhryc.system.dto.MenuData;
import com.gzhryc.system.dto.MenuSearch;
import com.gzhryc.system.dto.RoleSearch;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RoleController {
	static Logger log = Logger.getLogger( RoleController.class);

	@Route("/sys/role/list.html")
	public String list(HttpServletRequest request){
		request.setAttribute("statusList",DefaultEnum.Status.values());
		return "/sys/role/list.html";
	}
	
	@Route("/sys/role/list.data")
	public ListResult<Role> listData(HttpServletRequest request){
		ListResult<Role> result = new ListResult<Role>(DtoConstants.SUCCESS);
		RoleSearch search = WebUtils.getParameter(request,RoleSearch.class);
		Integer pageNo = WebUtils.getInteger(request,"page",1);
		Integer pageLimit = WebUtils.getInteger(request,"limit", WebConstants.PAGE_LIMIT);
		result.getBody().setTotal(RoleService.self().countBySearch(search));
		List<Role> data = RoleService.self().findBySearch(search, pageNo, pageLimit);
		if(data != null){
			result.getBody().setData(data);
		}
		return result;
	}
	
	@Route(value="/sys/role/select.data")
	public ListResult<Role> select(HttpServletRequest request) {
		ListResult<Role> response = new ListResult<Role>(DtoConstants.SUCCESS);
		List<Role> list = RoleService.self().findAll();
		response.getBody().setData(list);
		return response;
	}
	
	@Route("/sys/role/add.html")
	public String add(HttpServletRequest request){
		return "/sys/role/edit.html";
	}
	
	@Route(value="/sys/role/add.do",method="post")
	public AjaxResult doAdd(HttpServletRequest request){
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"新增失败");
		Role role = WebUtils.getParameter(request,Role.class);
		try {
			if(RoleService.self().add(role)){
				result.setCode(DtoConstants.SUCCESS, null);
			}
		} catch (LogicException e) {
			result.setMsg(e.getMessage());
		}
		return result;
	}
	
	@Route("/sys/role/update.html")
	public String update(HttpServletRequest request){
		Long id = WebUtils.getLong(request, "id");
		if(id != null) {
			Role role = RoleService.self().getById(id);
			WebUtils.setAttribute(request, role);
		}
		return "/sys/role/edit.html";
	}
	
	@Route(value="/sys/role/update.do",method="post")
	public AjaxResult doUpdate(HttpServletRequest request){
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"修改失败");
		Role role = WebUtils.getParameter(request,Role.class);
		try {
			if(RoleService.self().update(role)){
				result.setCode(DtoConstants.SUCCESS, null);
			}
		} catch (LogicException e) {
			log.error(e.getMessage(),e);
		}
		return result;
	}
	
	@Route("/sys/role/get.do")
	public AjaxResult get(HttpServletRequest request){
		AjaxResult result = new AjaxResult(-1,"获取角色失败");
		Long id = WebUtils.getLong(request,"id");
		if(id != null){
			Role role = RoleService.self().getById(id);
			if(role != null){
				result.setCode(DtoConstants.SUCCESS, null);
				result.setBody(role);
			}
		}
		return result;
	}
	
	@Route("/sys/role/del.do")
	public AjaxResult delete(HttpServletRequest request){
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"删除失败");
		Long id = WebUtils.getLong(request,"id");
		if(id != null){
			if(RoleService.self().deleteById(id)){
				result.setCode(DtoConstants.SUCCESS, null);
			}
		}
		return result;
	}
	
	@Route(value="/sys/role/menu/config.html",method="get")
	public String editMenu(HttpServletRequest request,HttpServletResponse response){
		Long roleId = WebUtils.getLong(request,"roleId");
		if(roleId != null){
			Role role = RoleService.self().getById(roleId);
			if(role != null){
				request.setAttribute("role",role);
				List<Menu> list = MenuService.self().findByRoleId(roleId);
				List<MenuData> data = new ArrayList<MenuData>();
				if(list != null){
					Map<Long,MenuData> map = new HashMap<Long,MenuData>();
					for(Menu item : list){
						MenuData temp = new MenuData();
						temp.setId(item.getId());
						temp.setName(item.getName());
						temp.setChildren(new ArrayList<MenuData>());
						map.put(temp.getId(), temp);  //临时保存
						if(item.getParentId() == null){
							data.add(temp);
						}else{
							MenuData parent = map.get(item.getParentId());
							if(parent != null){
								parent.getChildren().add(temp);
							}
						}
					}
				}
				request.setAttribute("data", JsonTools.toJson(data));
				MenuSearch search = new MenuSearch();
				request.setAttribute("rootMenuList", MenuService.self().findBySearchAndNotParent(search, 1, WebConstants.PAGE_LIMIT));
			}
		}
		return "/sys/role/configMenu.html";
	}
	
	@SuppressWarnings("unchecked")
	@Route(value="/sys/role/menu/config.do",method="post")
	public AjaxResult doEditMenu(HttpServletRequest request,HttpServletResponse response){
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"保存失败");
		Long roleId = WebUtils.getLong(request,"id");
		String data = request.getParameter("data");
		if(roleId != null && StringUtils.isNotBlank(data)){
			List<Map<String,Object>> list = JsonTools.fromJson(data, List.class);
			if(RoleService.self().editMenu(roleId, list)){
				result.setCode(DtoConstants.SUCCESS, null);
			}
		}
		return result;
	}
	
	@Route(value="/sys/role/menu/child.data")
	public AjaxResult findByChild(HttpServletRequest request){
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"获取失败");
		Long id = WebUtils.getLong(request,"id");
		if(id != null){
			MenuSearch search = new MenuSearch();
			search.setParentId(id);
			search.setTypes(new ArrayList<Integer>());
			search.getTypes().add(MenuEnum.Type.GroupAuthorization.index());
			search.getTypes().add(MenuEnum.Type.PathAuthorization.index());
			search.getTypes().add(MenuEnum.Type.FunAuthorization.index());
			List<Menu> data = MenuService.self().findBySearch(search, 1, WebConstants.PAGE_LIMIT);
			if(data == null || data.size() == 0){
				result.setCode(DtoConstants.NULL_DATA, "无数据");
			}else{
				result.setCode(DtoConstants.SUCCESS, null);
				result.setBody(data);
			}
		}
		return result;
	}
}
